package com.defysoft.waukidsbus.main;

import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.defysoft.waukidsbus.BaseActivity;
import com.defysoft.waukidsbus.R;

public class Main_Intro extends BaseActivity {

	private SharedPreferences login_code;
	private String sch_code = null;
	private String sch_name = null;
	final int SUCCESS = 10;
	final int FAIR = 9;
	final int LOGIN_STARTACTIVITY = 8; // 로그인으로.
	private final int UPDATE_VERSION = 7;
	private final int FAIR_VERSION = 6;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		setStartData();
	}

	@Override
	public void setStartData() {
		super.setStartData();

		((TextView) findViewById(R.id.WAUKIDSBUS_VERSION))
				.setText("appversion : " + getVersion());
		login_code = getSharedPreferences("login_code", MODE_PRIVATE);
		try {
			sch_code = login_code.getString("sch_code", null);
			sch_name = login_code.getString("sch_name", null);
		} catch (Exception e) {
			sch_code = null;
			sch_name = null;
		}
		if (sch_code == null || sch_code == "" || sch_name == null
				|| sch_name == "") {
			startNetwork(2); // 로그인으로.
		} else {
			startNetwork(1);// 쉐어프리퍼런스 내용있으면 체크.
		}
	}

	private String getVersion() { // 입력되는 버전값.
		PackageInfo pi = null;
		try {
			pi = getPackageManager().getPackageInfo(getPackageName(), 0);
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return pi.versionName;
	}

	@Override
	public void startThread(int choice) {
		super.startThread(choice);
		final int cho = choice;
		firstThread = new Thread(new Runnable() {
			@Override
			public void run() {
				if (checkVersion()) {
					switch (cho) {
					case 1:
						mainThread();
						break;
					case 2:
						try {
							Thread.sleep(2000);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
						onNetworkCallback(LOGIN_STARTACTIVITY, "");
						break;
					}
				}
			}
		});
		firstThread.start();

	}

	private void mainThread() {
		String msg = "";
		try {
			Thread.sleep(2000);
			JSONObject jsonObject = new JSONObject(publicHttpCallback(
					HTTP_LOGIN_CHECK, "code=" + sch_code + "&name=" + sch_name));
			if (jsonObject.getBoolean("success")) {
				msg = jsonObject.getString("payload");
				onNetworkCallback(SUCCESS, msg);
			} else {
				onNetworkCallback(FAIR, jsonObject.getString("message"));
			}
		} catch (Exception e) {
			onNetworkCallback(CATCH_EXCEPTION, e.toString());
		}
		;
	}

	@Override
	protected void handlingMessage(Message _message) {
		// TODO Auto-generated method stub
		super.handlingMessage(_message);
		switch (_message.what) {
		case CATCH_EXCEPTION:
			endDIal();
			if (firstThread == null) {
				firstThread.interrupt();
			}
			showPopup("네트워크오류", "네트워크 실패", 0);
			Toast.makeText(this, (String) _message.obj, Toast.LENGTH_LONG)
					.show();
			break;
		case FAIR:
			endDIal();
			if (firstThread == null) {
				firstThread.interrupt();
			}
			sendMessage(LOGIN_STARTACTIVITY);
			finish();
			break;
		case SUCCESS:
			endDIal();
			if (firstThread == null) {
				firstThread.interrupt();
			}
			startActivity(new Intent(this, Main_main.class));
			finish();
			break;
		case LOGIN_STARTACTIVITY: // 저장된 정보 없거나 잘못되서 로그인페이지로 이동
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			startActivity(new Intent(this, Main_login.class));
			finish();
			break;
		case FAIR_VERSION: // 버전 얻어오는데 실패
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			Toast.makeText(this, "버전 정보를 얻는데 실패했습니다.", Toast.LENGTH_LONG)
					.show();
			break;
		case UPDATE_VERSION: // 저장된 정보있는지 검사흐름
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			AlertDialog alert;
			AlertDialog.Builder builder = new AlertDialog.Builder(
					Main_Intro.this);
			builder.setMessage("버전이 바뀌었습니다 구글 스토어에서 업데이트해주세요")
					.setCancelable(false)
					.setPositiveButton("업데이트",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									try {
										startActivity(new Intent(
												Intent.ACTION_VIEW,
												Uri.parse("market://details?id="
														+ getPackageName())));
									} catch (android.content.ActivityNotFoundException anfe) {
										startActivity(new Intent(
												Intent.ACTION_VIEW,
												Uri.parse("http://play.google.com/store/apps/details?id="
														+ getPackageName())));
									}
								}
							})
					.setNegativeButton("종료",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									dialog.cancel();
									finish();
								}
							});
			alert = builder.create();
			alert.show();
			break;
		}
	}

	private boolean checkVersion() {

		String msg = "";
		try {
			JSONObject jsonObject = new JSONObject(publicHttpCallback(
					HTTP_VERSION, ""));
			if (jsonObject.getBoolean("success")) {
				msg = jsonObject.getString("payload");
				msg = new JSONObject(msg).getString("Waukidsbus");
				msg = msg.replace("d", ".");
				Log.i("ddd", Double.parseDouble(msg) + " " + Double.parseDouble(getVersion()));
				if (Double.parseDouble(msg)>Double.parseDouble(getVersion())) { // 학원정보저장.
					onNetworkCallback(UPDATE_VERSION, "");
					return false;
				} else {
					return true;
				}
				
			} else {
				onNetworkCallback(FAIR_VERSION, "");
				return false;
			}
		} catch (Exception e) {
			onNetworkCallback(FAIR_VERSION, e.toString());
		}
		;
		return false;
	}

}
